package com.wangzh.king.utils;

import com.wangzh.king.Exception.KingPropException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * 配置文件操作相关工具类
 * User: wangzh
 * Date: 2016/8/23
 * Time: 11:46
 */
public class PropUtils {

    private static Logger logger = LoggerFactory.getLogger(PropUtils.class);

    /**
     * 私有化构造器
     */
    private PropUtils(){}

    /**
     * 获得Properties对象
     * @return
     */
    public static Properties getProp(String path){
        InputStream inputStream = PropUtils.class.getResourceAsStream(path);
        Properties properties = new Properties();

        try {
            if(inputStream != null){
                properties.load(inputStream);
            }else{
                logger.error("["+path+"]路径的文件不存在!");
                throw new KingPropException("["+path+"]路径的文件不存在!");
            }
         } catch (IOException e) {
            logger.error("加载["+path+"]路径的文件出错!",e);
            throw new KingPropException(e);
        }
        return properties;
    }

    /**
     * 根据key获得值
     * @param properties
     * @param key
     * @return
     */
    public static String getValue(Properties properties, String key){
        return properties.getProperty(key);
    }


    /**
     * 根据key获得值 若不存在则返回默认值
     * @param properties
     * @param key
     * @param defaultValue
     * @return
     */
    public static String getValue(Properties properties, String key,String defaultValue){
        return properties.getProperty(key,defaultValue);
    }
}
